package com.zlp.spring.tx.service.v1.config;


import com.zlp.spring.tx.service.v1.util.TransactionalUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;

import java.util.Arrays;

@Aspect
@Component
// 开启AOP支持
// 该注解中会使用Import注解导入后置处理器及注册自定义Bean用来完成AOP功能
//@EnableAspectJAutoProxy
public class MyTransactional {

    @Autowired
    private TransactionalUtils transactionalUtils;

    @Pointcut("execution(* com.zlp.spring.tx.service.v1.service..*.*(..) )")
    public void pointCut() throws UnsupportedOperationException{
    }

    /**
     * 环绕通知
     *
     * @param joinpoint
     * @date: 2022/2/24 13:59
     * @return: java.lang.Object
     */
    @Around("pointCut()")
    public Object aroundTransactional(ProceedingJoinPoint joinpoint) {
        Object result = null;
        // 方法名称
//        String methodName = joinpoint.getSignature().getName();
//        System.out.println("执行Around，目标方法名称为：" + methodName);
//        // 目标方法的参数类型
//        Class[] parameterTypes = ((MethodSignature) joinpoint.getSignature()).getParameterTypes();
//        // 目标方法的入参
//        Object[] args = joinpoint.getArgs();
//        System.out.println("执行Around，方法入参为：" + Arrays.toString(args));

        TransactionStatus transactionStatus = transactionalUtils.beginTransaction();
        try {
            result = joinpoint.proceed();
            transactionalUtils.commit(transactionStatus);
        } catch (Throwable t) {
            transactionalUtils.rollback(transactionStatus);
            t.printStackTrace();
        }finally {
            return result;
        }
    }


}
